package Quene;

public class SeqQuene<T> implements Quene<T> {

    private Object element[];
    private int front,rear;
    private static final int MIN_CAPACITY=16;

    public SeqQuene() {
        this(MIN_CAPACITY);
    }

    public SeqQuene(int length) {
        if (length<MIN_CAPACITY)length=MIN_CAPACITY;
        this.element=new Object[length];
        this.front=this.rear=0;
    }

    @Override
    public boolean isEmpty() {
        return this.front==this.rear;
    }

    @Override
    public boolean add(T x) {
        if (x==null)return false;
        if (this.front==(this.rear+1)%element.length){
            Object[] temp = this.element;
            this.element = new Object[element.length*2];
            int j=0;
            for (int i=front;i!=front;i=(i+1)%temp.length)this.element[j++]=temp[i];
            this.front=0;
            this.rear=j;
        }
        this.element[rear]=x;
        rear=(rear+1)%element.length;
        return true;
    }

    @Override
    public T peek() {
        return this.isEmpty()?null: (T) this.element[front];
    }

    @Override
    public T poll() {
        if (this.isEmpty())return null;
        T temp = (T) this.element[front];
        front=(front+1)% element.length;
        return temp;
    }
}
